package com.zero.controller;

import com.zero.entity.Admin;
import com.zero.entity.FamilyMember;
import com.zero.entity.Notice;
import com.zero.mapper.FamilyMemberMapper;
import com.zero.service.NoticeService;
import com.zero.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 获取公告列表
     * @param notice
     * @param request
     * @return
     */
    @PostMapping("/list")
    public Result getNotice(@RequestBody Notice notice, HttpServletRequest request){
        Admin admin = (Admin) request.getAttribute("admin");
        if (admin != null && admin.getId() != null)
            return noticeService.selectSystemNotice(notice);
        return noticeService.selectFamilyNotice(notice, request);
    }

    @PostMapping("/add")
    public Result addNotice(@RequestBody Notice notice, HttpServletRequest request){
        Admin admin = (Admin) request.getAttribute("admin");
        if (admin != null && admin.getId() != null){
            notice.setType(0);
        }
        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember != null && familyMember.getId() != null){
            familyMember = familyMemberMapper.selectById(familyMember.getId());
            notice.setType(1);
            notice.setFamilyId(familyMember.getFamilyId());
        }
        return noticeService.addNotice(notice);
    }

    @GetMapping("/delete")
    public Result deleteNotice(@RequestParam("ids") String ids){
        return noticeService.deleteNotice(ids);
    }

    @PostMapping("/update")
    public Result updateNotice(@RequestBody Notice notice){
        return noticeService.updateNotice(notice);
    }

    @GetMapping("/systemNotice")
    public Result getSystemNotice(){
        return noticeService.selectSystemNotice();
    }

    @GetMapping("/familyNotice")
    public Result getFamilyNotice(HttpServletRequest request){
        return noticeService.selectFamilyNotice(request);
    }

}
